package com.samtech.spring.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.faces.context.ResponseWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.primefaces.context.RequestContext;
import org.primefaces.util.Constants;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

public class FixAjaxRedirectEntryPoint extends LoginUrlAuthenticationEntryPoint {

	@SuppressWarnings("serial")
	@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		
		if(isAjaxRequest(request)){
			
			//request.setAttribute(Constants.PARTIAL_UPDATE_PARAM,"@none");
			String url = this.buildRedirectUrlToLoginPage(request,response,authException);
			//FacesContext cxt = FacesContext.getCurrentInstance();
			//request.setAttribute("primefacesredirect", url);
			
			//ServletResponse response = (ServletResponse) facesContext.getExternalContext().getResponse();
			response.setContentType("text/xml");
			
			 PrintWriter writer = response.getWriter(); //facesContext.getResponseWriter();
			
				writer.write("<?xml version=\"1.0\" encoding=\"" + response.getCharacterEncoding() + "\"?>");
				writer.write("<partialResponse>");
				
				
					writer.write("<redirect-url>" + url + "</redirect-url>");
			
				
				writer.write("</partialResponse>");
			
			
		}else{
			super.commence(request, response, authException);
		}
	}
	
	protected boolean isAjaxRequest(ServletRequest request) {
		try {
			return null != request
					.getParameter(Constants.PARTIAL_REQUEST_PARAM);
		} catch (Exception e) {
			return false;
		}
	}

}
